package com.xiangyang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiangyang.annotations.OperationLog;
import com.xiangyang.entity.LoginUser;
import com.xiangyang.entity.User;
import com.xiangyang.entity.dto.Result;
import com.xiangyang.entity.vo.UserPermissionVO;
import com.xiangyang.mapper.IPermissionsMapper;
import com.xiangyang.mapper.IUserMapper;
import com.xiangyang.service.IPermissionsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class PermissionsServiceImpl implements IPermissionsService {
    private static final Logger logger = LoggerFactory.getLogger(PermissionsServiceImpl.class);
    @Autowired
    private IPermissionsMapper permissionsMapper;
    @Autowired
    private IUserMapper userMapper;

    @Override
    public Result<Object> getPermissionsList() {
        try {
            List<UserPermissionVO> permissionsList = permissionsMapper.selectPermissionsList();
            Map<String, Object> map = new HashMap<>();
            map.put("permissionsList", permissionsList);
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
             LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            map.put("userName",loginUser.getUserDetailInfo().getUserName());
            map.put("userType",loginUser.getUserDetailInfo().getUserType());
            return Result.ok(map);
        } catch (Exception e) {
            logger.error("获取权限列表失败", e);
            return Result.error("获取权限列表失败");
        }
    }


    @Override
    @Transactional
//    @OperationLog(title = "权限管理", businessType = "修改权限")
      public Result updatePermissions(UserPermissionVO upvo) {
        if (upvo == null) {
            return Result.error("信息不能为空");
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId, upvo.getUserId());
        User user = userMapper.selectOne(queryWrapper);
        if(user.getUserType()==1){
            return Result.error("超级管理员的权限不允许修改，若需要修改请联系软件开发人员。");

        }

        int result=permissionsMapper.updatePermissionsById(upvo);

        return result > 0 ? Result.ok() : Result.error("修改权限失败");
    }
}